<html>
<head>
    <meta charset="UTF-8">
    <title>流程配置编辑器</title>
    <link id="easyuiTheme" href="../../static/easyui/themes/bootstrap/easyui.css" rel="stylesheet" type="text/css"/>
    <link href="../../static/css/normalize.css?twitterbutton" rel="stylesheet" type="text/css"/>
    <link href="../../static/css/tricks.css?twitterbutton" rel="stylesheet" type="text/css"/>
    <link href="../../static/css/elusive-webfont.css?twitterbutton" rel="stylesheet" type="text/css"/>
    <link href="../../static/css/codemirror.css?twitterbutton" rel="stylesheet" type="text/css"/>
    <link href="../../static/css/screen.css?twitterbutton" rel="stylesheet" type="text/css"/>
    <link href="../../static/easyui/themes/icon.css" rel="stylesheet" type="text/css" />
    <script src="../../static/easyui/jquery.min.js" type="text/javascript"></script>
    <script src="../../static/easyui/jquery.cookie.js" type="text/javascript"></script>
    <script src="../../static/easyui/ui-theme.js" type="text/javascript"></script>
    <script src="../../static/easyui/jquery.easyui.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="../../static/easyui/jquery.easyui.ext.js" type="text/javascript" charset="utf-8"></script>
    <script src="../../static/easyui/locale/easyui-lang-zh_CN.js" type="text/javascript"></script>
    <script src="../../static/plugin/assets/jslib.util.js" type="text/javascript"></script>
    <script src="../../static/plugin/assets/jslib.jquery.ajax.js" type="text/javascript"></script>
    <script src="../../static/plugin/assets/jslib.easyui.util.js" type="text/javascript"></script>
    <script src="../../static/js/libs/jquery.cookie.min.js" type="text/javascript"></script>
    <script src="../../ffres/dict/all.js" type="text/javascript"></script>
    <link href="../../static/css/esaas-easyui-edit.css" rel="stylesheet" type="text/css" />
    <script src="../../static/js/konva.min.js" type="text/javascript"></script>
    <script src="../../static/js/uuid.v4.js" type="text/javascript"></script>
    <script src="../../static/js/flowchart.js" type="text/javascript"></script>
    <a href="" target="_blank" id="commonLink" name="commonLink"></a>
    <style>
        .tool-panel {
            text-align:left;
            background: #f8f8f8;
            border-bottom: solid 1px #d4d4d4;
        }
        .node-panel {
            margin: auto 5px;
            text-align: center;
        }
        .node-panel .node-drop {
            padding: 5px 15px;
            font-size: 16px;
            background-color: #f6f7ff;
            border: solid 2px #04679a;
            margin: 15px auto;
            width: 170px;
            height: 22px;
        }
    </style>
</head>
<body class="easyui-layout" scroll="no">
	<div data-options="region:'west',title:'流程编排面板'" style="width:283px;padding:1px;">
        <div class="node-panel"> </div>
	</div>
	<div data-options="region:'center',title:''" >
        <div style="text-align:center;" id="centerPanel">
            <div class="tool-panel" style="width: 100%; height: 26px;">
                <a onclick="javascript:saveNodes()" class="easyui-linkbutton" iconCls="icon-ok" plain="true">保存</a>
                <a  class="easyui-linkbutton" iconCls="icon-ok" plain="true">校验</a>
                <span style="color: #40a0ff">流程状态： 已校验 </span>
            </div>
            <div id="container" ></div>
        </div>
	</div>
    <script>

		var bpmId = $.getUrlParam('bpmId');
		var externalData, flow, currentNode, bpmBase;
		
        $(function () {
            var fixWindowHeight = function(){
                var h = $(window).height();
                var w = $(window).width();
                flow.container.stage.height(h - 38 -35);
                flow.container.stage.width(w- 283 - 30);
            };
			$(window).on('resize', fixWindowHeight);
			

            $.get(`../../api/bpm/base/infos/flowdata/${bpmId}`, null,
                function (data) {
                    externalData = data.rows;
                    $('title').text(externalData.BpmBaseInfo.bpmName);
                    $('#title').text(externalData.BpmBaseInfo.bpmName);
                    initFlowchart();
                    fixWindowHeight();
                }, "json");

            window.addEventListener("keydown", function(event) {
                if (!(event.which == 83 && event.ctrlKey)) return true;
                event.preventDefault();
                saveNodes();
                return false;
            });
        });

        function openTaskNode(event, node) {
            if (node && node.$data) {
                currentNode = node;
                if (currentNode.$data.bpmNodeId) {
                    $.restfulGet('../../api/plugin/define/' + currentNode.$data.bpmNodeCode,null,function(data){
                        if (data.rows && data.rows.pluginConfigUrl)
                            JLEUtil.createModalWin(`${node.$data.text}配置`, `${data.rows.pluginConfigUrl}?&nodeId=${node.$data.bpmNodeId}&bpmNodeCode=${node.$data.bpmNodeCode}&readonly=false`+'&bpmState='+$.getUrlParam("bpmState"));
                    },
                    function(jqXHR, status, errorThrown){
                        if (status == "error") {
                            currentNode.$data.bpmId = bpmId;
                            currentNode.$data.bpmNodeType =  currentNode.$data.type;
                            JLEUtil.createModalWinCustomSize('选择业务插件',
                                `popPluginDefine.html?&nodeId=${node.$data.bpmNodeId}&readonly=false`,0.8,0.8);

                        }
                    });
                } else {
                    //currentNode.$data.nodeId = node.id();
                    currentNode.$data.bpmId = bpmId;
                    currentNode.$data.bpmNodeType =  currentNode.$data.type;
                    JLEUtil.createModalWinCustomSize('选择业务插件',
                        `popPluginDefine.html?&nodeId=${node.$data.bpmNodeId}&readonly=false`,0.8,0.8);

                }
            }
        }

        function changeNodeTextHandler(event, node, newText, oldText, callback) {
            if (newText != oldText) {
                let nodeData = {
                    bpmNodeId : node.$data.bpmNodeId,
                    bpmNodeName : newText,
                    bpmId : node.$data.bpmId,
                };
                $.restfulPut('../../api/bpm/node/info', nodeData, function (data) {
                    callback(newText);
                }, function(){
                    $.messager.alert('提示', '修改节点名称失败', 'error');
                });
            }
        }

        function createNode(node) {
            if (!node.$data.bpmNodeId) {
                currentNode.$data.bpmNodeId = node.id();
                currentNode.$data.bpmId = bpmId;
                currentNode.$data.bpmNodeType =  currentNode.$data.type;
                onChoosePluginDefine({pluginName: node.$data.text})
            }
        }

        function openPluginApproveConf(event, node) {
            if (node && node.$data) {
                currentNode = node;
                createNode(node);
                JLEUtil.createModalWin(`${node.$data.text}列表信息`, 
                    `PluginApproveConfUpdate.html?&pluginConfId=${node.$data.bpmNodeId}&nodeId=${node.$data.bpmNodeId}&nodeType=${encodeURI(node.$data.type)}&readonly=false`);
            }
        }

        function openPluginContentionConf(event, node) {
            if (node && node.$data) {
                currentNode = node;
                createNode(node);
                JLEUtil.createModalWin(`${node.$data.text}列表信息`, 
                    `PluginContentionConfUpdate.html?&pluginConfId=${node.$data.bpmNodeId}&nodeId=${node.$data.bpmNodeId}&nodeType=${encodeURI(node.$data.type)}&readonly=false`);
            }
        }

        function openPluginCountersignConf(event, node) {
            if (node && node.$data) {
                currentNode = node;
                createNode(node);
                JLEUtil.createModalWin(`${node.$data.text}列表信息`, 
                    `PluginCountersignConfUpdate.html?&pluginConfId=${node.$data.bpmNodeId}&nodeId=${node.$data.bpmNodeId}&nodeType=${encodeURI(node.$data.type)}&readonly=false`);
            }
        }

        function openPluginAssignConf(event, node) {
            if (node && node.$data) {
                currentNode = node;
                createNode(node);
                JLEUtil.createModalWin(`${node.$data.text}列表信息`, 
                    `PluginAssignConfUpdate.html?&pluginConfId=${node.$data.bpmNodeId}&nodeId=${node.$data.bpmNodeId}&nodeType=${encodeURI(node.$data.type)}&readonly=false`);
            }
        }

        function openStartNode(event, node) {
            if (node && node.$data) {
                currentNode = node;
                createNode(node);
                JLEUtil.createModalWin(`${node.$data.text}列表信息`, 
                    `OsrvInoutInfoList.html?&appModelId=${node.$data.bpmNodeId}&nodeId=${node.$data.bpmNodeId}&nodeType=${encodeURI(node.$data.type)}&readonly=false`);
            }
        }
        function openEndNode(event, node) {
            if (node && node.$data) {
                currentNode = node;
                createNode(node);
                JLEUtil.createModalWin(`${node.$data.text}列表信息`, 
                    `OsrvInoutInfoList.html?&appModelId=${node.$data.bpmNodeId}&nodeId=${node.$data.bpmNodeId}&nodeType=${encodeURI(node.$data.type)}&readonly=false`);
            }
        }

        // 选择内部服务回调
        function onChoosePluginDefine(row) {
            var nodeData = {
				bpmNodeId: currentNode.id(),
				bpmId: bpmId,
				bpmNodeCode : row.pluginId,
				bpmNodeName : row.pluginName,
                text : row.pluginName,
            };
			updateNodeAfterSave(nodeData);
			currentNode.$data.bpmId = bpmId;
			currentNode.$data.bpmNodeId = currentNode.id();
			currentNode.$data.bpmNodeName = currentNode.$data.text;
			currentNode.$data.bpmNodeType = currentNode.$data.type;
            nodeData = {
				bpmNodeId : currentNode.$data.bpmNodeId,
				bpmNodeCode : currentNode.$data.bpmNodeCode,
				bpmNodeName : currentNode.$data.bpmNodeName,
				bpmNodeType : currentNode.$data.bpmNodeType,
				bpmId : currentNode.$data.bpmId,
                x : currentNode.x(),
                y : currentNode.y(),
                h : currentNode.$data.h,
                w : currentNode.$data.w
            };
            $.restfulPut('../../api/bpm/node/info', nodeData, function (data) {
                //window.parent.reloadList();
                //$.messager.alert('提示', '保存成功', 'info');
            });
            
        }

        // 退格键事件处理器
        function onDeleteKeyup(event, nodes, removeCallback) {
            if (nodes && nodes.length > 0) {
                $.messager.confirm('删除提示', '你确定要删除这个节点?', function (r) {
                    if (r) {
                        nodes.forEach(node => {
                            if (node.getClassName() == "Group") {
                                var jsonData = JSON.parse('{'+'"bpmNodeId":"' + node.$data.bpmNodeId + '"'+'}');
                                $.restfulDelete('../../api/bpm/node/info', jsonData, function(data) {
                                    removeCallback(nodes);
                                });
                            } else if (node.getClassName() == "Arrow") {
                                var jsonData = JSON.parse('{'+'"linkedId":"' + node.attrs.id + '"'+'}');
                                $.restfulDelete('../../api/bpm/linked/info', jsonData, function(data) {
                                    removeCallback(nodes);
                                });
                            } else {
                                removeCallback(nodes);
                            }
                        });
                    }
                });
            }
        }
        // 节点链接双击事件处理
        function onArrowDblclick(event, startNode, endNode) {
            var targetLinkedId = event.target.getId();
            if (targetLinkedId) {
                JLEUtil.createModalWin('外部模型节点链接条件列表', `OsrvLinkedCondList.html?&linkedId=${targetLinkedId}&readonly=false`);
            }   
        }

        // 初始化流程图
        function initFlowchart() {
            var panelNodes = [
                {
                    type: "N01",
                    text: "开始节点",
                    color: "#f6f7ff", // konva fill
                    borderColor: "#03689a", // konva stroke
                    // onClick: function (event, node) {},
                    // onDblclick: openStartNode,
                    // onDragstart: function (event, node) {},
                    // onDragmove: function (event, node) {},
                    // onDragend: function (event, node) {},
                    // onSelected: function (event, node) {}
                }, {
                    type: "N07",
                    text: "业务插件",
                    color: "#f6f7ff", // konva fill
                    borderColor: "#03689a", // konva stroke
                    // onClick: function (event, node) {},
                    onTextChange: changeNodeTextHandler,
                    onDblclick: openTaskNode,
                    contextmenu:[{
                        name: "删除",
                        click: function(e, group, nodeInfo){
                            onDeleteKeyup(e, [group], flow.removeNodesCallback.bind(flow));
                        }
                    }],
                    // onDragstart: function (event, node) {},
                    // onDragmove: function (event, node) {},
                    // onDragend: function (event, node) {},
                    // onSelected: function (event, node) {}
                }, {
                    type: "N99",
                    text: "结束节点",
                    color: "#f6f7ff", // konva fill
                    borderColor: "#03689a", // konva stroke
                    // onClick: function (event, node) {},
                    // onDblclick: openEndNode,
                    // onDragstart: function (event, node) {},
                    // onDragmove: function (event, node) {},
                    // onDragend: function (event, node) {},
                    // onSelected: function (event, node) {}
                }, ];
            // add nodepanel div
            panelNodes.forEach( (node, index)=>{
                var nodeDOM = $(`<div class="node-drop" draggable="true">${node.text}</div>`);
                $(nodeDOM).data('nodeData', node)
                $(nodeDOM).on('dragstart', function(e){
                    window.$$FLOWCHART_NODE_DATA = $(e.target).data('nodeData')
                })
                $('.node-panel').append(nodeDOM);
            });
            var h = $(window).height();
            var w = $(window).width();
            h = h - 38 -35;
            w = w- 283 - 30;
            flow = new Flowchart({
                hidePanel: true,
                height : h,
                width : w,
                container: "container",
                onDeleteKeyup: onDeleteKeyup,
                /* onArrowDblclick: onArrowDblclick, */
                panel: {
                    nodes: panelNodes
                }
            });
            if (!externalData) {
                return;
            }
            var nodeInfos = externalData.BpmNodeInfo || [];
            var linkeds = externalData.BpmLinkedInfo || [];
            var nodes = [],
                links = [];
			nodeInfos.forEach((element, index) => {
                var node = flow.factory("Node", {
                    x: element.x,
                    y: element.y,
                    id: element.bpmNodeId,
                    type: element.bpmNodeType,
                    text: element.bpmNodeName,
                    bpmNodeId : element.bpmNodeId,
					bpmNodeCode : element.bpmNodeCode,
					bpmNodeName : element.bpmNodeName,
					bpmNodeType : element.bpmNodeType,
					bpmId : element.bpmId
                });
                nodes.push(node);
            });
            linkeds.forEach(element => {
                var link = flow.factory("Link", {
                    id: element.linkedId,
                    points: [element.x1, element.y1, element.x2, element.y2],
                    startNode: element.sourceNodeId,
                    endNode: element.targetNodeId,
                    linkedId : element.linkedId,
					linkedType : element.linkedType,
					sourceNodeId : element.sourceNodeId,
					targetNodeId : element.targetNodeId,
					linkedDesc : element.linkedDesc,
					x1 : element.x1,
					y1 : element.y1,
					x2 : element.x2,
					y2 : element.y2
                });
                links.push(link);
            });
            flow.load({
                nodes: nodes,
                links: links
            });
        }

        function closeForm() {
            var bpmBaseInfo = externalData.BpmBaseInfo;
            var title = `${bpmBaseInfo.bpmName}修改`;
            window.parent.closeTab(title);
        }

        function updateNodeAfterSave(nodeData) {
            // nodeRefModelId nodename
            if (currentNode) {
                currentNode.$data.bpmNodeId = nodeData.bpmNodeId;
                currentNode.$data.bpmNodeCode = nodeData.bpmNodeCode;
                currentNode.$data.bpmNodeName = nodeData.bpmNodeName;
                currentNode.$data.text = nodeData.bpmNodeName;
                var nodeText = currentNode.findOne('.nodeText');
                nodeText.text(nodeData.bpmNodeName);
                currentNode.$data.x = currentNode.x();
                currentNode.$data.y = currentNode.y();
                currentNode.$data.h = nodeText.height();
                currentNode.$data.w = nodeText.width();
                flow.refresh();
            }
        }

        // 保存流程信息
        function saveNodes() {
            var flowData = flow.export();
            var nodes = flowData.nodes.map( el => {
				if (!el.$data.bpmNodeId) {
					el.$data.bpmId = bpmId;
					el.$data.bpmNodeId = el.attrs.id;
					el.$data.bpmNodeName = el.$data.text;
					el.$data.bpmNodeType = el.$data.type;
				}
                return {
					bpmNodeId : el.$data.bpmNodeId,
					bpmNodeCode : el.$data.bpmNodeCode,
					bpmNodeName : el.$data.bpmNodeName,
					bpmNodeType : el.$data.bpmNodeType,
					bpmId : el.$data.bpmId,
                    x : el.attrs.x,
                    y : el.attrs.y,
                    h : el.$data.h,
                    w : el.$data.w
                }
            });
            var links = flowData.links.map( el=>{
                return {
                    linkedId : el.attrs.id,
                    sourceNodeId : el.startNode,
                    targetNodeId : el.endNode,
                    x1 : el.attrs.points[0],
                    y1 : el.attrs.points[1],
                    x2 : el.attrs.points[2],
                    y2 : el.attrs.points[3]
                }
            });
            $.restfulPostJson(`../../api/bpm/base/infos/flowdata`, { BpmNodeInfo: nodes, BpmLinkedInfo: links},
            function(data){
                if (data.success) {
                    $.messager.alert('提示', '保存成功', 'info');
                } else {
                    $.messager.alert('提示', data.message, 'error');
                }
            }, 
            function(data){
                $.messager.alert('提示', '保存失败 ' + data.message, 'error');
            });
        }
	</script>
</body>
</html>
